Python Lists

Python Lists are an extremely versatile data type, the next of the Python data types we will explore.

Lists (type list) may not seem like from looking at them, but they are an extremely powerful data type. They can hold other Python data types, strings, floats, integers, lists, dictionaries, sets, and tuples. Lists are an ordered sequence of elements, so we can slice and index them to get the desired elements. They are also mutable, so we can change them by index or add new elements to a list. Let’s look at some examples of lists:

lst1 = [1,2,3]
lst2 = ['cat','dog','bird']
lst3 = ['boy', 50, 12.4]
lst4 = [1,2,3,[4,5,6],[7,8,9,[10,11,12]]]

We will focus on lst4 for our list slicing since that will give us some interesting output. Lists are indexed the same way as strings, so if we want the number 1, we will put in index 0

lst4[0]
1

Now, here is where some of the interesting things come in with this specific list. This list is a multi-dimensional list, which is a fancy way of saying it\\\’s a list of lists. What if we pulled back index 3, which you think would be the number 4

lst4[3] 
[4, 5, 6]

You get that whole second list in the list, so if we wanted number 5, our indexing would look like this:

lst4[3][1]
5

What if we wanted number 7? If we input 4 as our index

lst4[4]
[7, 8, 9, [10, 11, 12]]

We get back two lists. Since what is at index 4 is a list in a list. So if we want 7,

lst4[4][0]
7

How would we grab 11?

lst4[4][3][1]
11

This is why, if we look at how the list is constructed:

Breaking it down, the first index of 4 returns all the green:

lst4[4]
[7, 8, 9, [10, 11, 12]]

Now, 3 returns the inner list; once in 4, we count the index positions, so 7 would be index 0, 8 is index 1, and so on. Index 3 gives you the list 10, 11, 12

lst4[4][3]
[10, 11, 12]

And finally, we need to get 11. In this list, we want index 1

lst4[4][3][1]
11

With this, if you wanted to slice it and return 11 and 12:

lst4[4][3][1:]
[11, 12]

We can still do list slicing with nested lists and indexing.